<script setup lang="ts">
import type { IContextMenuItem } from '@vben-core/shadcn-ui';

import type { RasterService } from './index';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { computed, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';
import {
  ElCheck,
  ElCircleClose,
  ElDelete,
  ElFiles,
  ElSearch,
  ElView,
  IpSortOne,
} from '@vben/icons';

import { VbenContextMenu } from '@vben-core/shadcn-ui';
import { StorageManager } from '@vben-core/shared/cache';

import {
  ElButton,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElPopover,
  ElSpace,
  ElTag,
} from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { rasterServiceApi } from '#/api';
import { $t } from '#/locales';

import { tupianIcon } from './assets';
import { RasterPreviewDialog } from './components';

type SortType = 'default' | 'name' | 'publishTime' | 'type';
type OrderType = 'asc' | 'desc';

interface SortItemType {
  label: string;
  value: OrderType | SortType;
  active: boolean;
  divider?: boolean;
}

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});

const userId = storageManager.getItem<string>('userId');
const keyword = ref('');
const showRasterPreviewDialog = ref(false);
const currentSortMethod = ref<SortType>('default');
const currentSortOrder = ref<OrderType>('asc');
const currentRasterService = reactive({
  data: {} as RasterService,
});
const selectedRasterS = ref<RasterService[]>([]);
const sortOptions = ref<SortItemType[]>([
  {
    label: $t('page.resources.sortOptions.byDefault'),
    value: 'default',
    active: true,
  },
  {
    label: $t('page.resources.sortOptions.byServiceName'),
    value: 'name',
    active: false,
  },
  {
    label: $t('page.resources.sortOptions.byDate'),
    value: 'publishTime',
    active: false,
  },
  {
    label: $t('page.resources.sortOptions.byServiceType'),
    value: 'type',
    active: false,
  },
  {
    label: $t('page.resources.sortOptions.byAsc'),
    value: 'asc',
    active: true,
    divider: true,
  },
  {
    label: $t('page.resources.sortOptions.byDesc'),
    value: 'desc',
    active: false,
  },
]);

const realSortOptions = computed(() => {
  return sortOptions.value.map((option) => ({
    ...option,
    active:
      option.value === currentSortMethod.value ||
      option.value === currentSortOrder.value,
  }));
});

const selectedIds = computed(() => {
  return selectedRasterS.value.map((item) => item.id);
});

const selectedCount = computed(() => {
  return selectedRasterS.value.length;
});

const imageSrc = (type: string) => {
  switch (type) {
    default: {
      return tupianIcon;
    }
  }
};

const getServiceList = async (
  currentPage: number,
  pageSize: number,
  delay: number = 300,
) => {
  await new Promise((resolve) => setTimeout(resolve, delay));
  return rasterServiceApi.getRasterSList(
    userId as string,
    pageSize,
    currentPage,
    keyword.value,
  );
};

const gridOptions: VxeGridProps<RasterService> = {
  size: 'medium',
  height: '100%',
  showHeaderOverflow: true,
  checkboxConfig: {
    highlight: true,
    trigger: 'row',
    range: true,
    reserve: true,
  },
  rowConfig: {
    keyField: 'id',
    height: 55,
    isHover: true,
  },
  columns: [
    { type: 'checkbox', width: 80 },
    {
      field: 'name',
      title: '名称',
      width: '40%',
      align: 'left',
      sortable: true,
      slots: {
        default: 'icon-name',
      },
    },
    { field: 'type', title: '类型', sortable: true },
    { field: 'publishTime', title: '发布时间', sortable: true },
    { slots: { default: 'action' }, title: '操作' },
  ],
  pagerConfig: {
    pageSize: 10,
    pageSizes: [10, 15, 20, 50],
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return getServiceList(page.currentPage, page.pageSize);
      },
    },
  },
  toolbarConfig: {
    custom: true,
    refresh: {
      code: 'query',
    },
    zoom: true,
  },
};

const handleSelectionChange = () => {
  // eslint-disable-next-line no-use-before-define
  const selectRecords = gridApi.grid.getCheckboxRecords();
  // eslint-disable-next-line no-use-before-define
  const selectReserveRecords = gridApi.grid.getCheckboxReserveRecords();
  selectedRasterS.value = [...selectRecords, ...selectReserveRecords];
};

const handleSortChange = (field: SortType, order: OrderType) => {
  if (!order) {
    currentSortMethod.value = 'default';
    currentSortOrder.value = 'asc';
    return;
  }
  currentSortMethod.value = field;
  currentSortOrder.value = order;
};

const gridEvents: VxeGridListeners<RasterService> = {
  checkboxChange: () => handleSelectionChange(),
  checkboxAll: () => handleSelectionChange(),
  sortChange: ({ field, order }) =>
    handleSortChange(field as SortType, order as OrderType),
};

const [Grid, gridApi] = useVbenVxeGrid({ gridEvents, gridOptions });

const clearSelection = () => {
  selectedRasterS.value = [];
  gridApi.grid.clearCheckboxRow();
};

const handleSortData = (sortMethod: SortType, order: 'asc' | 'desc') => {
  if (sortMethod === 'default') {
    currentSortOrder.value = 'asc';
    gridApi.grid.clearSort();
    return;
  }
  gridApi.grid.setSort(
    {
      field: sortMethod,
      order,
    },
    true,
  );
};

const isOptionDisabled = (sortMethod: OrderType | SortType) => {
  return sortMethod === 'desc' && currentSortMethod.value === 'default';
};

const handleUpdateSort = (sortMethod: OrderType | SortType) => {
  if (
    sortMethod === currentSortMethod.value ||
    sortMethod === currentSortOrder.value
  ) {
    return;
  }
  if (sortMethod === 'asc' || sortMethod === 'desc') {
    currentSortOrder.value = sortMethod;
  } else {
    currentSortMethod.value = sortMethod;
  }
  handleSortData(currentSortMethod.value, currentSortOrder.value);
};

const previewRasterService = (data: RasterService) => {
  currentRasterService.data = data;
  showRasterPreviewDialog.value = true;
};

const handleClosePreviewDialog = () => {
  showRasterPreviewDialog.value = false;
};

const openConfirmDialog = () => {
  return ElMessageBox.confirm(
    $t('page.resources.deleteResourceConfirmMessage'),
    $t('page.resources.deleteResourceConfirmTitle'),
    {
      confirmButtonText: $t('page.resources.confirmButtonText'),
      cancelButtonText: $t('page.resources.cancelButtonText'),
      type: 'warning',
    },
  );
};

const deleteRasterService = async (sourceId: any) => {
  openConfirmDialog()
    .then(async () => {
      await rasterServiceApi.deleteRasterService(userId as string, sourceId);
      await gridApi.query();
      ElMessage.success('栅格资源删除成功！');
    })
    .catch(() => {
      ElMessage.info($t('page.resources.deleteCancelledMessage'));
    });
};

const deleteServiceList = (sourceIds: string[]) => {
  if (sourceIds.length === 0) {
    ElMessage.error($t('page.resources.noRasterServiceResource'));
    return;
  }
  const deletePromises = sourceIds.map((sourceId) =>
    rasterServiceApi.deleteRasterService(userId as string, sourceId),
  );
  Promise.all(deletePromises)
    .then((responses) => {
      const successCount = responses.length;
      gridApi.query();
      if (successCount === sourceIds.length) {
        ElMessage.success(
          $t('page.resources.deleteSuccessMessage', { successCount }),
        );
      } else {
        const failedCount = sourceIds.length - successCount;
        ElMessage.error(
          $t('page.resources.deleteResultMessage', {
            successCount,
            failedCount,
          }),
        );
      }
    })
    .catch((error) => {
      console.error('请求出错:', error);
      ElMessage.error($t('page.resources.deleteErrorMessage'));
    });
};

const pileDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning($t('page.resources.noRasterServiceSelectedMessage'));
    return;
  }
  openConfirmDialog()
    .then(() => {
      deleteServiceList(selectedIds.value);
    })
    .catch(() => {
      ElMessage.info($t('page.resources.deleteCancelledMessage'));
    });
};
const getContextMenus = (data: RasterService): IContextMenuItem[] => [
  {
    text: '预览',
    icon: ElView,
    handler: () => {
      previewRasterService(data);
    },
    key: 'preview',
  },
  {
    text: '删除',
    icon: ElDelete,
    handler: () => {
      deleteRasterService(data.id);
    },
    key: 'delete',
  },
];
</script>

<template>
  <Page
    oncontextmenu="return false"
    onselectstart="return false"
    description="由栅格数据发布的栅格服务资源，用于地图可视化"
    title="栅格服务"
    auto-content-height
  >
    <Grid
      table-title="服务资源列表"
      table-title-help="包含（tiff、png）格式的栅格数据服务"
      @checkbox-change="handleSelectionChange"
    >
      <template #toolbar-tools>
        <div class="multi-delete flex items-center">
          <div class="flex items-center" v-if="selectedIds.length > 0">
            <div class="flex items-center">
              <ElIcon>
                <ElFiles />
              </ElIcon>
              &nbsp;
              <span>
                {{ $t('page.resources.selectedTitle', { selectedCount }) }}：
              </span>
            </div>
            <div
              class="w-[200px] overflow-hidden text-ellipsis whitespace-nowrap"
            >
              <ElPopover
                v-for="rasterS in selectedRasterS"
                :key="rasterS.id"
                :disabled="selectedRasterS.length < 3"
                placement="top-start"
                width="250"
                trigger="hover"
              >
                <template #reference>
                  <ElTag
                    class="cursor-pointer"
                    size="large"
                    @click="previewRasterService(rasterS)"
                  >
                    {{
                      rasterS.name.length > 10
                        ? `${rasterS.name.slice(0, 10)}...`
                        : rasterS.name
                    }}
                  </ElTag>
                </template>
                <ElSpace wrap size="small">
                  <ElTag
                    v-for="item in selectedRasterS"
                    style="cursor: pointer"
                    size="default"
                    :key="item.id"
                    @click="previewRasterService(item)"
                  >
                    {{ item.name }}
                  </ElTag>
                </ElSpace>
              </ElPopover>
            </div>
          </div>
          <ElDivider direction="vertical" border-style="hidden" />
          <ElButton
            v-if="selectedRasterS.length > 0"
            size="default"
            plain
            :icon="ElCircleClose"
            @click="clearSelection"
          >
            取消
          </ElButton>
          <ElButton
            v-if="selectedRasterS.length > 0"
            class="mr-4"
            size="default"
            plain
            :title="$t('page.resources.delete')"
            type="danger"
            :icon="ElDelete"
            @click="pileDelete"
          >
            删除
          </ElButton>
        </div>
        <div class="toolbar flex items-center">
          <ElInput
            v-model="keyword"
            size="default"
            :placeholder="$t('page.resources.searchPlaceholderr')"
            clearable
            @clear="() => gridApi.reload()"
            @keyup.enter="() => gridApi.reload()"
          >
            <template #append>
              <ElButton @click="() => gridApi.reload()" default>
                <ElIcon> <ElSearch /> </ElIcon>
              </ElButton>
            </template>
          </ElInput>
          <ElDropdown placement="bottom-end" class="ml-3 flex items-center">
            <ElButton :icon="IpSortOne" circle />
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem
                  v-for="option in realSortOptions"
                  :key="option.value"
                  :divided="option.divider"
                  :disabled="isOptionDisabled(option.value)"
                  @click="() => handleUpdateSort(option.value)"
                >
                  <span class="w-20">{{ option.label }}</span>
                  <ElIcon v-if="option.active">
                    <ElCheck />
                  </ElIcon>
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </div>
      </template>
      <template #icon-name="{ row }">
        <VbenContextMenu
          :menus="getContextMenus"
          :handler-data="row"
          :modal="false"
        >
          <div class="flex cursor-pointer items-center">
            <img :src="imageSrc(row.type)" class="mr-4 h-10 w-10" />
            <span class="overflow-hidden text-ellipsis whitespace-nowrap">
              {{ row.name }}
            </span>
          </div>
        </VbenContextMenu>
      </template>
      <template #action="{ row }">
        <ElButton
          type="primary"
          plain
          round
          @click="
            (e) => {
              e.stopPropagation();
              previewRasterService(row);
            }
          "
        >
          {{ $t('page.resources.preview') }}
        </ElButton>
        <ElButton
          type="danger"
          round
          plain
          @click="
            (e) => {
              e.stopPropagation();
              deleteRasterService(row.id);
            }
          "
        >
          {{ $t('page.resources.delete') }}
        </ElButton>
      </template>
    </Grid>
    <!-- 预览对话框 -->
    <RasterPreviewDialog
      v-if="showRasterPreviewDialog"
      :is-dialog-show="showRasterPreviewDialog"
      :current-raster-data="currentRasterService.data"
      @close-preview-dialog="handleClosePreviewDialog"
      @show-preview-dialog="previewRasterService"
    />
  </Page>
</template>
